#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time		:2018/3/6 9:24
# @Author	:RNone
import json
from json.decoder import JSONDecodeError
import logging
from requests_toolbelt.multipart.encoder import MultipartEncoder

from api.login import login


class common_bulk_insert(login):
	def get_login_session(self, caseDict):
		'''获取登陆后的requests对象'''
		session = self.do_login(caseDict)  # 获取登陆后的session
		return session

	def test_bulk_insert_data(self, caseDict):
		'''数据查询测试'''
		session = self.get_login_session(caseDict)
		'''获取页面verify'''
		host = 'http://' + caseDict['host']
		r = session.get(url=host + '/DataCenters')
		verify = self.find_verify(r.text)
		'''执行查询vpn信息'''
		data = MultipartEncoder(
			fields={
				'indexName': caseDict['params']['indexName'],
				'key_field': caseDict['params']['key_field'],
				'defultField': caseDict['params']['defultField'],
				'module': str(caseDict['params']['module']),
				'__RequestVerificationToken': verify,
				'file': (
					'filename',
					open(
						caseDict['params']['file'],
						'rb'),
					'text/plain')
			}
		)
		logging.debug('发送文件导入测试数据')
		r = session.post(
			url=host + '/Common/PostBulkInsert',
			data=data,
			headers={'Content-Type': data.content_type}
		)
		try:
			data = json.loads(r.text)
		except JSONDecodeError as e:
			self.write_error(e)
			data = r.text
		caseDict['response'] = data
		result = self.bulk_insert_result(r.text)
		if caseDict['expect'] == result:
			caseDict['result'] = 'PASS'
		else:
			caseDict['result'] = 'FAIL'
		return caseDict

	def bulk_insert_result(self, content):
		'''数据查询结果校验'''
		logging.debug('校验文件导入结果')
		if '批量新增成功' in content:
			return 'succ'
		else:
			return 'fail'


if __name__ == '__main__':
	params = {'host': '192.168.60.186'}
	csa = common_bulk_insert()
	csa.test_bulk_insert_data(params)
